<template>
  <div>
    <!-- 地图容器 -->
    <div id="incomeAndCostContainer"></div>

    <!-- 查询表单区域 -->
    <el-card id="extend" v-show="!isHidden" @click="hidden">+</el-card>

    <el-card id="searchCard" v-show="isHidden">
      <div id="hiddenButton" @click="hidden">-</div>
      <!-- 城市选择器 -->
      <el-select
        v-model="searchProvince"
        placeholder="Select"
        size="large"
        @change="provinceChanged"
      >
        <el-option
          v-for="item in cityOption"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>

      <!--多选框  -->
      <div id="checkbox">
        <el-checkbox v-model="country">全体居民</el-checkbox>
        <el-checkbox v-model="towns">城市居民</el-checkbox>
        <el-checkbox v-model="village">农村居民</el-checkbox>
      </div>

      <!-- 标签切换视图 -->
      <el-tabs v-model="activeName" class="demo-tabs">
        <!-- 表格 -->
        <el-tab-pane label="表格" name="table">
          <el-table
            :data="incomeAndCostData"
            height="250"
            style="width: 100%"
            :default-sort="{ prop: 'year', order: 'descending' }"
          >
            <el-table-column prop="year" label="年份" width="180" sortable />
            <el-table-column
              prop="income_country"
              label="全体居民平均收入"
              width="180"
              v-if="country"
              sortable
            />
            <el-table-column
              prop="income_towns"
              label="城镇居民平均收入"
              width="180"
              v-if="towns"
              sortable
            />
            <el-table-column
              prop="income_village"
              label="农村居民平均收入"
              width="180"
              v-if="village"
              sortable
            />
            <el-table-column
              prop="cost_country"
              label="全体居民平均支出"
              width="180"
              v-if="country"
              sortable
            />
            <el-table-column
              prop="cost_towns"
              label="城镇居民平均支出"
              width="180"
              v-if="towns"
              sortable
            />
            <el-table-column
              prop="cost_village"
              label="农村居民平均支出"
              width="180"
              v-if="village"
              sortable
            />
          </el-table>
        </el-tab-pane>
        <!-- 折线图 -->
        <el-tab-pane label="折线图" name="line">
          <div id="lineChartContainer" ref="lineChartContainer"></div>
        </el-tab-pane>

        <!-- 城市及农村收入对比 -->
        <el-tab-pane label="城乡净收入对比" name="lineChart_compare">
          <div id="lineChartContainer_compare"></div>
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<script setup>
import {
  reactive,
  ref,
  onActivated,
  onDeactivated,
  watch,
  onMounted,
  nextTick,
} from "vue";
import { shallowRef } from "@vue/reactivity";
import { createRegion } from "@/tools/createRegion.js";
import { ElMessage } from "element-plus";
import * as echarts from "echarts";
import AMapLoader from "@amap/amap-jsapi-loader";
import { cityOption } from "@/tools/cityOptions.js";
import { getIncomeAndCostData } from "@/networks/residentsLive/getIncomeAndCostData.js";
window._AMapSecurityConfig = {
  //高德地图API安全码
  securityJsCode: "7a147469fc71afc2c2540196e2453b2b",
};
let map = shallowRef(null); //地图
let searchProvince = ref(null); //城市选择器的值
let country = ref(true);
let towns = ref(true);
let village = ref(true);
let activeName = ref("table"); //标签页绑定值
let incomeAndCostData = reactive([]);
// let lineChartContainer = null;
let isHidden = ref(true);

// 初始化地图函数
let initMap = function () {
  if (map.value != null) {
    map.value.destroy();
    map.value.clearMap();
  }
  AMapLoader.load({
    key: "2b45c6a7655404e69a9b856504d8625c", // 申请好的Web端开发者Key，首次调用 load 时必填
    version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
  }).then((AMap) => {
    map.value = new AMap.Map("incomeAndCostContainer", {
      viewMode: "3D", //是否为3D地图模式
      zoom: 10, //初始化地图级别
      center: [117.301291, 31.844148], //初始化地图中心点位置
      mapStyle: "amap://styles/45311ae996a8bea0da10ad5151f72979",
      mapStyle: "amap://styles/dark",
    });
    // 加载插件
    AMap.plugin(
      ["AMap.ToolBar", "AMap.Geolocation", "AMap.DistrictSearch"],
      function () {
        map.value.addControl(new AMap.Geolocation());
      }
    );

    // 操作地图
    if (searchProvince.value != null) {
      createRegion(searchProvince.value, map.value);
    }
  });
};

// 获取数据
const getIncomeAndCostDataByProvince = async function () {
  try {
    const { data: res } = await getIncomeAndCostData({
      city: searchProvince.value,
    });
    if (res.status != 200) {
      return ElMessage.error("查询数据失败，请重试");
    } else {
      incomeAndCostData.length = 0;
      res.data.map((i) => {
        incomeAndCostData.push(i);
      });
      //   console.log(incomeAndCostData);
    }
  } catch (err) {
    console.log(err);
  }
};

// 创建折线图
function creatLineChart() {
  let lineChartContainer = document.querySelector("#lineChartContainer");
  // console.log(incomeAndCostData)
  if (lineChartContainer == null || incomeAndCostData.length == 0) {
    return;
  } else {
    echarts.dispose(lineChartContainer); //清空图表容器
    let lineChart = echarts.init(lineChartContainer);
    let cost_country = [],
      cost_towns = [],
      cost_village = [],
      income_country = [],
      income_towns = [],
      income_village = [],
      net_income = []; //净收入
    for (let i = 0; i < incomeAndCostData.length; i++) {
      income_country.unshift(incomeAndCostData[i].income_country);
      income_towns.unshift(incomeAndCostData[i].income_towns);
      income_village.unshift(incomeAndCostData[i].income_village);
      cost_country.unshift(incomeAndCostData[i].cost_country);
      cost_towns.unshift(incomeAndCostData[i].cost_towns);
      cost_village.unshift(incomeAndCostData[i].cost_village);
      net_income.unshift(
        incomeAndCostData[i].income_country - incomeAndCostData[i].cost_country
      );
    }
    lineChart.setOption({
      //图表配置项
      title: {
        text: `2012-2020${searchProvince.value}居民平均收入支出情况`,
      },
      toolbox: {
        show: true,
        feature: {
          dataZoom: {
            yAxisIndex: "none",
          },
          dataView: { readOnly: false },
          magicType: { type: ["line", "bar"] },
          restore: {},
          saveAsImage: {},
        },
      },
      tooltip: {
        trigger: "axis",
        axisPointer: {
          type: "shadow",
        },
      },
      grid: {
        top: "100px",
      },
      legend: {
        left: "100px",
        top: "30px",
      },
      xAxis: {
        name: "年份",
        data: [2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020],
        type: "category",
        boundaryGap: false,
      },
      yAxis: {
        name: "收入（支出）/元",
        type: "value",
        offset: "20",
      },
      series: [
        {
          name: "收入",
          type: "line",
          data: income_country,
          markPoint: {
            data: [
              { type: "max", name: "Max" },
              { type: "min", name: "Min" },
            ],
          },
        },
        {
          name: "支出",
          type: "line",
          data: cost_country,
          markPoint: {
            data: [
              { type: "max", name: "Max" },
              { type: "min", name: "Min" },
            ],
          },
        },
        {
          name: "净收入",
          type: "line",
          data: net_income,
          markPoint: {
            data: [
              { type: "max", name: "Max" },
              { type: "min", name: "Min" },
            ],
          },
        },
      ],
    });
  }
}

// 创建城乡对比图
let createLineChartContainer_compare = function () {
  let lineChartContainer = document.querySelector(
    "#lineChartContainer_compare"
  );
  // console.log(incomeAndCostData)
  if (lineChartContainer == null || incomeAndCostData.length == 0) {
    return;
  } else {
    echarts.dispose(lineChartContainer); //清空图表容器
    let lineChart = echarts.init(lineChartContainer);
    let net_income_towns = [],
      net_income_village = []; //净收入
    for (let i = 0; i < incomeAndCostData.length; i++) {
      net_income_towns.unshift(
        incomeAndCostData[i].income_towns - incomeAndCostData[i].cost_towns
      );
      net_income_village.unshift(
        incomeAndCostData[i].income_village - incomeAndCostData[i].cost_village
      );
    }
    lineChart.setOption({
      //图表配置项
      title: {
        text: `2012-2020${searchProvince.value}城乡居民净收入对比`,
      },
      toolbox: {
        show: true,
        feature: {
          dataZoom: {
            yAxisIndex: "none",
          },
          dataView: { readOnly: false },
          magicType: { type: ["line", "bar"] },
          restore: {},
          saveAsImage: {},
        },
      },
      tooltip: {
        trigger: "axis",
        axisPointer: {
          type: "shadow",
        },
      },
      grid: {
        top: "100px",
      },
      legend: {
        left: "100px",
        top: "30px",
      },
      xAxis: {
        name: "年份",
        data: [2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020],
        type: "category",
        boundaryGap: false,
      },
      yAxis: {
        name: "收入（支出）/元",
        type: "value",
        offset: "20",
      },
      series: [
        {
          name: "城市净收入",
          type: "line",
          data: net_income_towns,
          areaStyle: {},
          markPoint: {
            data: [
              { type: "max", name: "Max" },
              { type: "min", name: "Min" },
            ],
          },
        },
        {
          name: "农村净收入",
          type: "line",
          data: net_income_village,
          areaStyle: {},
          markPoint: {
            data: [
              { type: "max", name: "Max" },
              { type: "min", name: "Min" },
            ],
          },
        },
      ],
    });
  }
};

function hidden() {
  isHidden.value = !isHidden.value;
}

// 生命周期
onActivated(() => {
  initMap();
});
onDeactivated(() => {
  map.value?.destroy();
  map.value?.clearMap();
});

onMounted(() => {
  // lineChartContainer = document.querySelector("#lineChartContainer");
});
// 监听城市选择变化
let provinceChanged = async function () {
  initMap();
  await getIncomeAndCostDataByProvince();
  nextTick(() => {
    if (activeName.value == "line") {
      creatLineChart();
    } else if (activeName.value == "lineChart_compare") {
      createLineChartContainer_compare();
    }
  });
  //   console.log("触发了");
};

// 监听tab变化，重新渲染图表
watch(activeName, (val) => {
  nextTick(() => {
    if (val == "line") {
      creatLineChart();
    } else if (val == "lineChart_compare") {
      createLineChartContainer_compare();
    }
  });
});
</script>

<style lang="less" scoped>
#incomeAndCostContainer {
  width: calc(100vw - 200px);
  height: calc(100vh - 3rem);
  position: absolute;
  top: 3rem;
  left: 200px;
}

#searchCard {
  position: absolute;
  z-index: 2;
  top: 5rem;
  left: calc(1.5rem + 200px);
  #lineChartContainer {
    width: 50vw;
    height: 50vh;
    margin: 20px 50px;
  }
  #lineChartContainer_compare {
    width: 50vw;
    height: 50vh;
    margin: 20px 50px;
  }
}


#hiddenButton {
  position: absolute;
  right: 20px;
  font-size: 3rem;
  top: -10px;
  cursor: pointer;
}

#extend {
  position: absolute;
  z-index: 2;
  top: 5rem;
  left: calc(1.5rem + 200px);
  font-size: 2rem;
  cursor: pointer;
}
</style>
